#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 @Author: Monox
 @Email: 627201584@qq.com
 @FileName: monox_WorldOrder.py
 @DateTime: 2024/11/19 22:11
 @SoftWare: PyCharm
"""
import json
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
import pymysql
from fastapi.staticfiles import StaticFiles  # 导入静态文件模块

app = FastAPI(
    title="湾豚工单系统V2",
    docs_url="/docs",
    swagger_ui_parameters={"lang": "zh"}  # 设置 Swagger UI 语言为中文
)

# 挂载 static 文件夹
app.mount("/static", StaticFiles(directory="static"), name="static")

# 从配置文件中加载数据库配置
def load_config():
    with open("config.json", "r", encoding="utf-8") as f:
        config = json.load(f)
    return config["db_config"]

# 实例化数据库配置参数
db_config = load_config()


# 数据库连接
def get_db_connection():
    conn = pymysql.connect(
        host=db_config["host"],
        user=db_config["user"],
        password=db_config["password"],
        database=db_config["database"],
        charset='utf8mb4'
    )
    return conn


# 数据模型
class TicketCreate(BaseModel):
    title: str
    description: str
    submitter: str

class TicketAssign(BaseModel):
    ticket_id: int
    assignee: str

class TicketClose(BaseModel):
    ticket_id: int

class TicketUpdate(BaseModel):
    ticket_id: int
    recover: str

# 路由：创建工单
@app.post("/create_ticket")
async def create_ticket(ticket: TicketCreate):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(
        "INSERT INTO tickets (title, description, submitter, status) VALUES (%s, %s, %s, %s)",
        (ticket.title, ticket.description, ticket.submitter, 'open')
    )
    conn.commit()
    cursor.close()
    conn.close()
    return {"message": "工单已创建"}

# 路由：更新工单回复
@app.post("/update_recover")
async def update_recover(ticket: TicketUpdate):
    conn = get_db_connection()
    cursor = conn.cursor()
    try:
        # 更新工单的 recover 字段
        cursor.execute(
            "UPDATE tickets SET recover = %s WHERE id = %s",
            (ticket.recover, ticket.ticket_id)
        )
        conn.commit()
        if cursor.rowcount == 0:
            return {"message": "未找到指定工单", "success": False}
        return {"message": "回复已更新", "success": True}
    except Exception as e:
        conn.rollback()
        return {"message": f"更新失败: {e}", "success": False}
    finally:
        cursor.close()
        conn.close()


# 路由：分派工单
@app.post("/assign_ticket")
async def assign_ticket(ticket: TicketAssign):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(
        "UPDATE tickets SET assignee = %s, status = %s WHERE id = %s",
        (ticket.assignee, 'in_progress', ticket.ticket_id)
    )
    conn.commit()
    cursor.close()
    conn.close()
    return {"message": "工单已分派"}


# 路由：关闭工单
@app.post("/close_ticket")
async def close_ticket(ticket: TicketClose):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute(
        "UPDATE tickets SET status = %s WHERE id = %s",
        ('closed', ticket.ticket_id)
    )
    conn.commit()
    cursor.close()
    conn.close()
    return {"message": "工单已关闭"}


# 路由：获取所有工单
@app.get("/tickets")
async def get_tickets():
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM tickets")  # 查询所有字段
    columns = [desc[0] for desc in cursor.description]  # 获取所有列名
    tickets = cursor.fetchall()
    ticket_list = [dict(zip(columns, ticket)) for ticket in tickets]  # 将每一行数据与列名结合，生成字典
    cursor.close()
    conn.close()
    return {"tickets": ticket_list}


# 路由：获取单个工单
@app.get("/ticket/{ticket_id}")
async def get_ticket(ticket_id: int):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM tickets WHERE id = %s", (ticket_id,))
    columns = [desc[0] for desc in cursor.description]
    ticket = cursor.fetchone()
    cursor.close()
    conn.close()
    if ticket:
        return {"ticket": dict(zip(columns, ticket))}
    else:
        raise HTTPException(status_code=404, detail="工单未找到")


@app.get("/")
async def home():
    return {"message": "欢迎访问湾豚工单系统！"}

# # 工单状态映射
# ticket_status_enum = {
#     "open": "已提交",
#     "in_progress": "处理中",
#     "closed": "已关闭",
#     "all": "全部"
# }

# 路由：分页获取工单
@app.get("/tickets_paginated")
async def get_tickets_paginated(
        page: int = Query(1, ge=1),
        page_size: int = Query(10, ge=1, le=100),
        status: str = Query('all', enum=['all', 'open', 'in_progress', 'closed'])  # 添加 status 参数
):
    conn = get_db_connection()
    cursor = conn.cursor()

    # 根据状态过滤
    if status == 'all':
        # 如果是 'all' 则不加状态过滤条件
        cursor.execute("SELECT * FROM tickets ORDER BY id DESC LIMIT %s OFFSET %s", (page_size, (page - 1) * page_size))
    else:
        # 如果有状态过滤条件，则加上 WHERE 状态条件
        cursor.execute(
            "SELECT * FROM tickets WHERE status = %s ORDER BY id DESC LIMIT %s OFFSET %s",
            (status, page_size, (page - 1) * page_size)
        )

    columns = [desc[0] for desc in cursor.description]
    tickets = cursor.fetchall()

    # 查询总数以便前端了解数据规模
    if status == 'all':
        cursor.execute("SELECT COUNT(*) FROM tickets")
    else:
        cursor.execute("SELECT COUNT(*) FROM tickets WHERE status = %s", (status,))
    total_count = cursor.fetchone()[0]

    cursor.close()
    conn.close()

    return {
        "tickets": [dict(zip(columns, ticket)) for ticket in tickets],
        "total_count": total_count,
        "page": page,
        "page_size": page_size
    }

'''
启用服务：uvicorn monox_WorldOrder:app --reload
前端页面：http://127.0.0.1:8000/static/index.html
'''
